<?php
session_start();

require_once "config.php"; // for the admin and user password constant values

// check for login session
if (!isset($_SESSION['user'])) {
    // check for post values
    if (!$_POST) {
        // print form
        print_login_form();
        exit();
    }
    else
    {
        // process login request
        if (valid_login($_POST)) {
            // set session
            $_SESSION['user'] = 'admin';
            header('Location: index.php');
        }
        else
        {
            unset($_SESSION['user']);
            print_login_form();
        }
    }
}
else
{
    if ($_SESSION['user'] == 'admin') {
        // this person is logged in, redirect to main page
        header('Location: index.php');
    }
    else
    {
        // print login form
        unset($_SESSION['user']);
        print_login_form();
        exit();
    }
}

// prints out a login form
function print_login_form() {
?>
  <div class='login-form'>
    <form method='post'>
      <table>
        <tr>
          <th>user:</th>
          <td><input type='text' name='user' size='15' maxlength='25'/></td>
        </tr>
        <tr>
          <th>password:</th>
          <td><input type='password' name='password' size='15' maxlength='25'/></td>
        </tr>
        <tr>
          <td colspan='2'><input type='submit' value='log in'/></td>
        </tr>
      </table>
    </form>  
  </div>
<?php
}

// checks to see if posted value is correct, if yes, returns true; returns false otherwise
function valid_login($_POST) {
    if ($_POST['user'] == ADMINUSER && md5($_POST['password']) == ADMINPASSWORD) {
        return true;
    }
    else
    {
        return false;
    }
}


